home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume22 / gawk2.11 / part11 < prev    next >
Encoding:
Internet Message Format  |  1990-06-07  |  54.8 KB

  1. Subject:  v22i097:  GNU AWK, version 2.11, Part11/16
  2. Newsgroups: comp.sources.unix
  3. Approved: rsalz@uunet.UU.NET
  4. X-Checksum-Snefru: e4e7be9b 6cd97e54 9e8ebd46 c352a92b
  5.  
  6. Submitted-by: "Arnold D. Robbins" <arnold@unix.cc.emory.edu>
  7. Posting-number: Volume 22, Issue 97
  8. Archive-name: gawk2.11/part11
  9.  
  10. #! /bin/sh
  11. # This is a shell archive.  Remove anything before this line, then feed it
  12. # into a shell via "sh file" or similar.  To overwrite existing files,
  13. # type "sh file -c".
  14. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  15. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  16. # Contents:  ./gawk.1 ./io.c ./missing.d/memcpy.c
  17. # Wrapped by rsalz@litchi.bbn.com on Wed Jun  6 12:24:56 1990
  18. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  19. echo If this archive is complete, you will see the following message:
  20. echo '          "shar: End of archive 11 (of 16)."'
  21. if test -f './gawk.1' -a "${1}" != "-c" ; then 
  22.   echo shar: Will not clobber existing file \"'./gawk.1'\"
  23. else
  24.   echo shar: Extracting \"'./gawk.1'\" \(33549 characters\)
  25.   sed "s/^X//" >'./gawk.1' <<'END_OF_FILE'
  26. X.TH GAWK 1 "August 24 1989" "Free Software Foundation"
  27. X.SH NAME
  28. Xgawk \- pattern scanning and processing language
  29. X.SH SYNOPSIS
  30. X.B gawk
  31. X.ig
  32. X[
  33. X.B \-d
  34. X] [
  35. X.B \-D
  36. X]
  37. X..
  38. X[
  39. X.B \-a
  40. X] [
  41. X.B \-e
  42. X] [
  43. X.B \-c
  44. X] [
  45. X.B \-C
  46. X] [
  47. X.B \-V
  48. X] [
  49. X.BI \-F\^ fs
  50. X] [
  51. X.B \-v
  52. X.IR var = val
  53. X]
  54. X.B \-f
  55. X.I program-file
  56. X[
  57. X.B \-\^\-
  58. X] file .\^.\^.
  59. X.br
  60. X.B gawk
  61. X.ig
  62. X[
  63. X.B \-d
  64. X] [
  65. X.B \-D
  66. X]
  67. X..
  68. X[
  69. X.B \-a
  70. X] [
  71. X.B \-e
  72. X] [
  73. X.B \-c
  74. X] [
  75. X.B \-C
  76. X] [
  77. X.B \-V
  78. X] [
  79. X.BI \-F\^ fs
  80. X] [
  81. X.B \-v
  82. X.IR var = val
  83. X] [
  84. X.B \-\^\-
  85. X]
  86. X.I program-text
  87. Xfile .\^.\^.
  88. X.SH DESCRIPTION
  89. X.I Gawk
  90. Xis the GNU Project's implementation of the AWK programming language.
  91. XIt conforms to the definition and description of the language in
  92. X.IR "The AWK Programming Language" ,
  93. Xby Aho, Kernighan, and Weinberger,
  94. Xwith the additional features defined in the System V Release 4 version
  95. Xof \s-1UNIX\s+1
  96. X.IR awk ,
  97. Xand some GNU-specific extensions.
  98. X.PP
  99. XThe command line consists of options to
  100. X.I gawk
  101. Xitself, the AWK program text (if not supplied via the
  102. X.B \-f
  103. Xoption), and values to be made
  104. Xavailable in the
  105. X.B ARGC
  106. Xand
  107. X.B ARGV
  108. Xpre-defined AWK variables.
  109. X.PP
  110. X.I Gawk
  111. Xaccepts the following options, which should be available on any implementation
  112. Xof the AWK language.
  113. X.TP
  114. X.BI \-F fs
  115. XUse
  116. X.I fs
  117. Xfor the input field separator (the value of the
  118. X.B FS
  119. Xpredefined
  120. Xvariable).
  121. X.TP
  122. X\fB\-v\fI var\fR\^=\^\fIval\fR
  123. XAssign the value
  124. X.IR val ,
  125. Xto the variable
  126. X.IR var ,
  127. Xbefore execution of the program begins.
  128. XSuch variable values are available to the
  129. X.B BEGIN
  130. Xblock of an AWK program.
  131. X.TP
  132. X.BI \-f " program-file"
  133. XRead the AWK program source from the file
  134. X.IR program-file ,
  135. Xinstead of from the first command line argument.
  136. XMultiple
  137. X.B \-f
  138. Xoptions may be used.
  139. X.TP
  140. X.B \-\^\-
  141. XSignal the end of options. This is useful to allow further arguments to the
  142. XAWK program itself to start with a ``\-''.
  143. XThis is mainly for consistency with the argument parsing convention used
  144. Xby most other System V programs.
  145. X.PP
  146. XThe following options are specific to the GNU implementation.
  147. X.TP
  148. X.B \-a
  149. XUse AWK style regular expressions as described in the book.
  150. XThis is the current default, but may not be when the POSIX P1003.2
  151. Xstandard is finalized.
  152. XIt is orthogonal to
  153. X.BR \-c .
  154. X.TP
  155. X.B \-e
  156. XUse
  157. X.IR egrep (1)
  158. Xstyle regular expressions as described in POSIX standard.
  159. XThis may become the default when the POSIX P1003.2
  160. Xstandard is finalized.
  161. XIt is orthogonal to
  162. X.BR \-c .
  163. X.TP
  164. X.B \-c
  165. XRun in
  166. X.I compatibility
  167. Xmode.  In compatibility mode,
  168. X.I gawk
  169. Xbehaves identically to \s-1UNIX\s+1
  170. X.IR awk ;
  171. Xnone of the GNU-specific extensions are recognized.
  172. X.TP
  173. X.B \-C
  174. XPrint the short version of the GNU copyright information message on
  175. Xthe error output.
  176. XThis option may disappear in a future version of
  177. X.IR gawk .
  178. X.TP
  179. X.B \-V
  180. XPrint version information for this particular copy of
  181. X.I gawk
  182. Xon the error output.
  183. XThis is useful mainly for knowing if the current copy of
  184. X.I gawk
  185. Xon your system
  186. Xis up to date with respect to whatever the Free Software Foundation
  187. Xis distributing.
  188. XThis option may disappear in a future version of
  189. X.IR gawk .
  190. X.PP
  191. XAny other options are flagged as illegal, but are otherwise ignored.
  192. X.PP
  193. XAn AWK program consists of a sequence of pattern-action statements
  194. Xand optional function definitions.
  195. X.RS
  196. X.PP
  197. X\fIpattern\fB    { \fIaction statements\fB }\fR
  198. X.br
  199. X\fBfunction \fIname\fB(\fIparameter list\fB) { \fIstatements\fB }\fR
  200. X.RE
  201. X.PP
  202. X.I Gawk
  203. Xfirst reads the program source from the
  204. X.IR program-file (s)
  205. Xif specified, or from the first non-option argument on the command line.
  206. XThe
  207. X.B \-f
  208. Xoption may be used multiple times on the command line.
  209. X.I Gawk
  210. Xwill read the program text as if all the
  211. X.IR program-file s
  212. Xhad been concatenated together.  This is useful for building libraries
  213. Xof AWK functions, without having to include them in each new AWK
  214. Xprogram that uses them.  To use a library function in a file from a
  215. Xprogram typed in on the command line, specify
  216. X.B /dev/tty
  217. Xas one of the
  218. X.IR program-file s,
  219. Xtype your program, and end it with a
  220. X.B ^D
  221. X(control-d).
  222. X.PP
  223. XThe environment variable
  224. X.B AWKPATH
  225. Xspecifies a search path to use when finding source files named with
  226. Xthe 
  227. X.B \-f
  228. Xoption.  If this variable does not exist, the default path is
  229. X\fB".:/usr/lib/awk:/usr/local/lib/awk"\fR.
  230. XIf a file name given to the
  231. X.B \-f
  232. Xoption contains a ``/'' character, no path search is performed.
  233. X.PP
  234. X.I Gawk
  235. Xcompiles the program into an internal form,
  236. Xexecutes the code in the
  237. X.B BEGIN
  238. Xblock(s) (if any),
  239. Xand then proceeds to read
  240. Xeach file named in the
  241. X.B ARGV
  242. Xarray.
  243. XIf there are no files named on the command line,
  244. X.I gawk
  245. Xreads the standard input.
  246. X.PP
  247. XIf a ``file'' named on the command line has the form
  248. X.IB var = val
  249. Xit is treated as a variable assignment. The variable
  250. X.I var
  251. Xwill be assigned the value
  252. X.IR val .
  253. XThis is most useful for dynamically assigning values to the variables
  254. XAWK uses to control how input is broken into fields and records. It
  255. Xis also useful for controlling state if multiple passes are needed over
  256. Xa single data file.
  257. X.PP
  258. XFor each line in the input,
  259. X.I gawk
  260. Xtests to see if it matches any
  261. X.I pattern
  262. Xin the AWK program.
  263. XFor each pattern that the line matches, the associated
  264. X.I action
  265. Xis executed.
  266. X.SH VARIABLES AND FIELDS
  267. XAWK variables are dynamic; they come into existence when they are
  268. Xfirst used. Their values are either floating-point numbers or strings,
  269. Xdepending upon how they are used. AWK also has one dimension
  270. Xarrays; multiply dimensioned arrays may be simulated.
  271. XThere are several pre-defined variables that AWK sets as a program
  272. Xruns; these will be described as needed and summarized below.
  273. X.SS Fields
  274. X.PP
  275. XAs each input line is read,
  276. X.I gawk
  277. Xsplits the line into
  278. X.IR fields ,
  279. Xusing the value of the
  280. X.B FS
  281. Xvariable as the field separator.
  282. XIf
  283. X.B FS
  284. Xis a single character, fields are separated by that character.
  285. XOtherwise,
  286. X.B FS
  287. Xis expected to be a full regular expression.
  288. XIn the special case that
  289. X.B FS
  290. Xis a single blank, fields are separated
  291. Xby runs of blanks and/or tabs.
  292. XNote that the value of
  293. X.B IGNORECASE
  294. X(see below) will also affect how fields are split when
  295. X.B FS
  296. Xis a regular expression.
  297. X.PP
  298. XEach field in the input line may be referenced by its position,
  299. X.BR $1 ,
  300. X.BR $2 ,
  301. Xand so on.
  302. X.B $0
  303. Xis the whole line. The value of a field may be assigned to as well.
  304. XFields need not be referenced by constants:
  305. X.RS
  306. X.PP
  307. X.ft B
  308. Xn = 5
  309. X.br
  310. Xprint $n
  311. X.ft R
  312. X.RE
  313. X.PP
  314. Xprints the fifth field in the input line.
  315. XThe variable
  316. X.B NF
  317. Xis set to the total number of fields in the input line.
  318. X.PP
  319. XReferences to non-existent fields (i.e. fields after
  320. X.BR $NF ),
  321. Xproduce the null-string. However, assigning to a non-existent field
  322. X(e.g., 
  323. X.BR "$(NF+2) = 5" )
  324. Xwill increase the value of
  325. X.BR NF ,
  326. Xcreate any intervening fields with the null string as their value, and
  327. Xcause the value of
  328. X.B $0
  329. Xto be recomputed, with the fields being separated by the value of
  330. X.BR OFS .
  331. X.SS Built-in Variables
  332. X.PP
  333. XAWK's built-in variables are:
  334. X.PP
  335. X.RS
  336. X.TP \l'\fBIGNORECASE\fR'
  337. X.B ARGC
  338. Xthe number of command line arguments (does not include options to
  339. X.IR gawk ,
  340. Xor the program source).
  341. X.TP \l'\fBIGNORECASE\fR'
  342. X.B ARGV
  343. Xarray of command line arguments. The array is indexed from
  344. X0 to
  345. X.B ARGC
  346. X\- 1.
  347. XDynamically changing the contents of
  348. X.B ARGV
  349. Xcan control the files used for data.
  350. X.TP \l'\fBIGNORECASE\fR'
  351. X.B ENVIRON
  352. XAn array containing the values of the current environment.
  353. XThe array is indexed by the environment variables, each element being
  354. Xthe value of that variable (e.g., \fBENVIRON["HOME"]\fP might be
  355. X.BR /u/arnold ).
  356. XChanging this array does not affect the environment seen by programs which
  357. X.I gawk
  358. Xspawns via redirection or the
  359. X.B system
  360. Xfunction.
  361. X(This may change in a future version of
  362. X.IR gawk .)
  363. X.TP \l'\fBIGNORECASE\fR'
  364. X.B FILENAME
  365. Xthe name of the current input file.
  366. XIf no files are specified on the command line, the value of
  367. X.B FILENAME
  368. Xis ``\-''.
  369. X.TP \l'\fBIGNORECASE\fR'
  370. X.B FNR
  371. Xthe input record number in the current input file.
  372. X.TP \l'\fBIGNORECASE\fR'
  373. X.B FS
  374. Xthe input field separator, a blank by default.
  375. X.TP \l'\fBIGNORECASE\fR'
  376. X.B IGNORECASE
  377. XControls the case-sensitivity of all regular expression operations. If
  378. X.B IGNORECASE
  379. Xhas a non-zero value, then pattern matching in rules,
  380. Xfield splitting with
  381. X.BR FS ,
  382. Xregular expression
  383. Xmatching with
  384. X.B ~
  385. Xand
  386. X.BR !~ ,
  387. Xand the
  388. X.BR gsub() ,
  389. X.BR index() ,
  390. X.BR match() ,
  391. X.BR split() ,
  392. Xand
  393. X.B sub()
  394. Xpre-defined functions will all ignore case when doing regular expression
  395. Xoperations.  Thus, if
  396. X.B IGNORECASE
  397. Xis not equal to zero,
  398. X.B /aB/
  399. Xmatches all of the strings \fB"ab"\fP, \fB"aB"\fP, \fB"Ab"\fP,
  400. Xand \fB"AB"\fP.
  401. XAs with all AWK variables, the initial value of
  402. X.B IGNORECASE
  403. Xis zero, so all regular expression operations are normally case-sensitive.
  404. X.TP \l'\fBIGNORECASE\fR'
  405. X.B NF
  406. Xthe number of fields in the current input record.
  407. X.TP \l'\fBIGNORECASE\fR'
  408. X.B NR
  409. Xthe total number of input records seen so far.
  410. X.TP \l'\fBIGNORECASE\fR'
  411. X.B OFMT
  412. Xthe output format for numbers,
  413. X.B %.6g
  414. Xby default.
  415. X.TP \l'\fBIGNORECASE\fR'
  416. X.B OFS
  417. Xthe output field separator, a blank by default.
  418. X.TP \l'\fBIGNORECASE\fR'
  419. X.B ORS
  420. Xthe output record separator, by default a newline.
  421. X.TP \l'\fBIGNORECASE\fR'
  422. X.B RS
  423. Xthe input record separator, by default a newline.
  424. X.B RS
  425. Xis exceptional in that only the first character of its string
  426. Xvalue is used for separating records. If
  427. X.B RS
  428. Xis set to the null string, then records are separated by
  429. Xblank lines.
  430. XWhen
  431. X.B RS
  432. Xis set to the null string, then the newline character always acts as
  433. Xa field separator, in addition to whatever value
  434. X.B FS
  435. Xmay have.
  436. X.TP \l'\fBIGNORECASE\fR'
  437. X.B RSTART
  438. Xthe index of the first character matched by
  439. X.BR match() ;
  440. X0 if no match.
  441. X.TP \l'\fBIGNORECASE\fR'
  442. X.B RLENGTH
  443. Xthe length of the string matched by
  444. X.BR match() ;
  445. X\-1 if no match.
  446. X.TP \l'\fBIGNORECASE\fR'
  447. X.B SUBSEP
  448. Xthe character used to separate multiple subscripts in array
  449. Xelements, by default \fB"\e034"\fR.
  450. X.RE
  451. X.SS Arrays
  452. X.PP
  453. XArrays are subscripted with an expression between square brackets
  454. X.RB ( [ " and " ] ).
  455. XIf the expression is an expression list
  456. X.RI ( expr ", " expr " ...)"
  457. Xthen the array subscript is a string consisting of the
  458. Xconcatenation of the (string) value of each expression,
  459. Xseparated by the value of the
  460. X.B SUBSEP
  461. Xvariable.
  462. XThis facility is used to simulate multiply dimensioned
  463. Xarrays. For example:
  464. X.PP
  465. X.RS
  466. X.ft B
  467. Xi = "A" ;\^ j = "B" ;\^ k = "C"
  468. X.br
  469. Xx[i, j, k] = "hello, world\en"
  470. X.ft R
  471. X.RE
  472. X.PP
  473. Xassigns the string \fB"hello, world\en"\fR to the element of the array
  474. X.B x
  475. Xwhich is indexed by the string \fB"A\e034B\e034C"\fR. All arrays in AWK
  476. Xare associative, i.e. indexed by string values.
  477. X.PP
  478. XThe special operator
  479. X.B in
  480. Xmay be used in an
  481. X.B if
  482. Xor
  483. X.B while
  484. Xstatement to see if an array has an index consisting of a particular
  485. Xvalue.
  486. X.PP
  487. X.RS
  488. X.ft B
  489. X.nf
  490. Xif (val in array)
  491. X    print array[val]
  492. X.fi
  493. X.ft
  494. X.RE
  495. X.PP
  496. XIf the array has multiple subscripts, use
  497. X.BR "(i, j) in array" .
  498. X.PP
  499. XThe
  500. X.B in
  501. Xconstruct may also be used in a
  502. X.B for
  503. Xloop to iterate over all the elements of an array.
  504. X.PP
  505. XAn element may be deleted from an array using the
  506. X.B delete
  507. Xstatement.
  508. X.SS Variable Typing
  509. X.PP
  510. XVariables and fields
  511. Xmay be (floating point) numbers, or strings, or both. How the
  512. Xvalue of a variable is interpreted depends upon its context. If used in
  513. Xa numeric expression, it will be treated as a number, if used as a string
  514. Xit will be treated as a string.
  515. X.PP
  516. XTo force a variable to be treated as a number, add 0 to it; to force it
  517. Xto be treated as a string, concatenate it with the null string.
  518. X.PP
  519. XThe AWK language defines comparisons as being done numerically if
  520. Xpossible, otherwise one or both operands are converted to strings and
  521. Xa string comparison is performed.
  522. X.PP
  523. XUninitialized variables have the numeric value 0 and the string value ""
  524. X(the null, or empty, string).
  525. X.SH PATTERNS AND ACTIONS
  526. XAWK is a line oriented language. The pattern comes first, and then the
  527. Xaction. Action statements are enclosed in
  528. X.B {
  529. Xand
  530. X.BR } .
  531. XEither the pattern may be missing, or the action may be missing, but,
  532. Xof course, not both. If the pattern is missing, the action will be
  533. Xexecuted for every single line of input.
  534. XA missing action is equivalent to
  535. X.RS
  536. X.PP
  537. X.B "{ print }"
  538. X.RE
  539. X.PP
  540. Xwhich prints the entire line.
  541. X.PP
  542. XComments begin with the ``#'' character, and continue until the
  543. Xend of the line.
  544. XBlank lines may be used to separate statements.
  545. XNormally, a statement ends with a newline, however, this is not the
  546. Xcase for lines ending in
  547. Xa ``,'', ``{'', ``?'', ``:'', ``&&'', or ``||''.
  548. XLines ending in
  549. X.B do
  550. Xor
  551. X.B else
  552. Xalso have their statements automatically continued on the following line.
  553. XIn other cases, a line can be continued by ending it with a ``\e'',
  554. Xin which case the newline will be ignored.
  555. X.PP
  556. XMultiple statements may
  557. Xbe put on one line by separating them with a ``;''.
  558. XThis applies to both the statements within the action part of a
  559. Xpattern-action pair (the usual case),
  560. Xand to the pattern-action statements themselves.
  561. X.SS Patterns
  562. XAWK patterns may be one of the following:
  563. X.PP
  564. X.RS
  565. X.nf
  566. X.B BEGIN
  567. X.B END
  568. X.BI / "regular expression" /
  569. X.I "relational expression"
  570. X.IB pattern " && " pattern
  571. X.IB pattern " || " pattern
  572. X.IB pattern " ? " pattern " : " pattern
  573. X.BI ( pattern )
  574. X.BI ! " pattern"
  575. X.IB pattern1 ", " pattern2"
  576. X.fi
  577. X.RE
  578. X.PP
  579. X.B BEGIN
  580. Xand
  581. X.B END
  582. Xare two special kinds of patterns which are not tested against
  583. Xthe input.
  584. XThe action parts of all
  585. X.B BEGIN
  586. Xpatterns are merged as if all the statements had
  587. Xbeen written in a single
  588. X.B BEGIN
  589. Xblock. They are executed before any
  590. Xof the input is read. Similarly, all the
  591. X.B END
  592. Xblocks are merged,
  593. Xand executed when all the input is exhausted (or when an
  594. X.B exit
  595. Xstatement is executed).
  596. X.B BEGIN
  597. Xand
  598. X.B END
  599. Xpatterns cannot be combined with other patterns in pattern expressions.
  600. X.B BEGIN
  601. Xand
  602. X.B END
  603. Xpatterns cannot have missing action parts.
  604. X.PP
  605. XFor
  606. X.BI / "regular expression" /
  607. Xpatterns, the associated statement is executed for each input line that matches
  608. Xthe regular expression.
  609. XRegular expressions are the same as those in
  610. X.IR egrep (1),
  611. Xand are summarized below.
  612. X.PP
  613. XA
  614. X.I "relational expression"
  615. Xmay use any of the operators defined below in the section on actions.
  616. XThese generally test whether certain fields match certain regular expressions.
  617. X.PP
  618. XThe
  619. X.BR && ,
  620. X.BR || ,
  621. Xand
  622. X.B !
  623. Xoperators are logical AND, logical OR, and logical NOT, respectively, as in C.
  624. XThey do short-circuit evaluation, also as in C, and are used for combining
  625. Xmore primitive pattern expressions. As in most languages, parentheses
  626. Xmay be used to change the order of evaluation.
  627. X.PP
  628. XThe
  629. X.B ?\^:
  630. Xoperator is like the same operator in C. If the first pattern is true
  631. Xthen the pattern used for testing is the second pattern, otherwise it is
  632. Xthe third. Only one of the second and third patterns is evaluated.
  633. X.PP
  634. XThe 
  635. X.IB pattern1 ", " pattern2"
  636. Xform of an expression is called a range pattern.
  637. XIt matches all input lines starting with a line that matches
  638. X.IR pattern1 ,
  639. Xand continuing until a line that matches
  640. X.IR pattern2 ,
  641. Xinclusive. It does not combine with any other sort of pattern expression.
  642. X.SS Regular Expressions
  643. XRegular expressions are the extended kind found in
  644. X.IR egrep .
  645. XThey are composed of characters as follows:
  646. X.RS
  647. X.TP \l'[^abc...]'
  648. X.I c
  649. Xmatches the non-metacharacter
  650. X.IR c .
  651. X.TP \l'[^abc...]'
  652. X.I \ec
  653. Xmatches the literal character
  654. X.IR c .
  655. X.TP \l'[^abc...]'
  656. X.B .
  657. Xmatches any character except newline.
  658. X.TP \l'[^abc...]'
  659. X.B ^
  660. Xmatches the beginning of a line or a string.
  661. X.TP \l'[^abc...]'
  662. X.B $
  663. Xmatches the end of a line or a string.
  664. X.TP \l'[^abc...]'
  665. X.BI [ abc... ]
  666. Xcharacter class, matches any of the characters
  667. X.IR abc... .
  668. X.TP \l'[^abc...]'
  669. X.BI [^ abc... ]
  670. Xnegated character class, matches any character except
  671. X.I abc...
  672. Xand newline.
  673. X.TP \l'[^abc...]'
  674. X.IB r1 | r2
  675. Xalternation: matches either
  676. X.I r1
  677. Xor
  678. X.IR r2 .
  679. X.TP \l'[^abc...]'
  680. X.I r1r2
  681. Xconcatenation: matches
  682. X.IR r1 ,
  683. Xand then
  684. X.IR r2 .
  685. X.TP \l'[^abc...]'
  686. X.IB r +
  687. Xmatches one or more
  688. X.IR r 's. 
  689. X.TP \l'[^abc...]'
  690. X.IB r *
  691. Xmatches zero or more
  692. X.IR r 's. 
  693. X.TP \l'[^abc...]'
  694. X.IB r ?
  695. Xmatches zero or one
  696. X.IR r 's. 
  697. X.TP \l'[^abc...]'
  698. X.BI ( r )
  699. Xgrouping: matches
  700. X.IR r .
  701. X.RE
  702. XThe escape sequences that are valid in string constants (see below)
  703. Xare also legal in regular expressions.
  704. X.SS Actions
  705. XAction statements are enclosed in braces,
  706. X.B {
  707. Xand
  708. X.BR } .
  709. XAction statements consist of the usual assignment, conditional, and looping
  710. Xstatements found in most languages. The operators, control statements,
  711. Xand input/output statements
  712. Xavailable are patterned after those in C.
  713. X.SS Operators
  714. X.PP
  715. XThe operators in AWK, in order of increasing precedence, are
  716. X.PP
  717. X.RS
  718. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  719. X.B "= += \-= *= /= %= ^="
  720. XAssignment. Both absolute assignment
  721. X.BI ( var " = " value )
  722. Xand operator-assignment (the other forms) are supported.
  723. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  724. X.B ?:
  725. XThe C conditional expression. This has the form
  726. X.IB expr1 " ? " expr2 " : " expr3\c
  727. X\&. If
  728. X.I expr1
  729. Xis true, the value of the expression is
  730. X.IR expr2 ,
  731. Xotherwise it is
  732. X.IR expr3 .
  733. XOnly one of
  734. X.I expr2
  735. Xand
  736. X.I expr3
  737. Xis evaluated.
  738. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  739. X.B ||
  740. Xlogical OR.
  741. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  742. X.B &&
  743. Xlogical AND.
  744. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  745. X.B "~ !~"
  746. Xregular expression match, negated match.
  747. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  748. X.B "< <= > >= != =="
  749. Xthe regular relational operators.
  750. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  751. X.I blank
  752. Xstring concatenation.
  753. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  754. X.B "+ \-"
  755. Xaddition and subtraction.
  756. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  757. X.B "* / %"
  758. Xmultiplication, division, and modulus.
  759. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  760. X.B "+ \- !"
  761. Xunary plus, unary minus, and logical negation.
  762. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  763. X.B ^
  764. Xexponentiation (\fB**\fR may also be used, and \fB**=\fR for
  765. Xthe assignment operator).
  766. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  767. X.B "++ \-\^\-"
  768. Xincrement and decrement, both prefix and postfix.
  769. X.TP \l'\fB= += \-= *= /= %= ^=\fR'
  770. X.B $
  771. Xfield reference.
  772. X.RE
  773. X.SS Control Statements
  774. X.PP
  775. XThe control statements are
  776. Xas follows:
  777. X.PP
  778. X.RS
  779. X.nf
  780. X\fBif (\fIcondition\fB) \fIstatement\fR [ \fBelse\fI statement \fR]
  781. X\fBwhile (\fIcondition\fB) \fIstatement \fR
  782. X\fBdo \fIstatement \fBwhile (\fIcondition\fB)\fR
  783. X\fBfor (\fIexpr1\fB; \fIexpr2\fB; \fIexpr3\fB) \fIstatement\fR
  784. X\fBfor (\fIvar \fBin\fI array\fB) \fIstatement\fR
  785. X\fBbreak\fR
  786. X\fBcontinue\fR
  787. X\fBdelete \fIarray\^\fB[\^\fIindex\^\fB]\fR
  788. X\fBexit\fR [ \fIexpression\fR ]
  789. X\fB{ \fIstatements \fB}
  790. X.fi
  791. X.RE
  792. X.SS "I/O Statements"
  793. X.PP
  794. XThe input/output statements are as follows:
  795. X.PP
  796. X.RS
  797. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  798. X.BI close( filename )
  799. Xclose file (or pipe, see below).
  800. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  801. X.B getline
  802. Xset
  803. X.B $0
  804. Xfrom next input record; set
  805. X.BR NF ,
  806. X.BR NR ,
  807. X.BR FNR .
  808. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  809. X.BI "getline <" file
  810. Xset
  811. X.B $0
  812. Xfrom next record of
  813. X.IR file ;
  814. Xset
  815. X.BR NF .
  816. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  817. X.BI getline " var"
  818. Xset
  819. X.I var
  820. Xfrom next input record; set
  821. X.BR NF ,
  822. X.BR FNR .
  823. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  824. X.BI getline " var" " <" file
  825. Xset
  826. X.I var
  827. Xfrom next record of
  828. X.IR file .
  829. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  830. X.B next
  831. XStop processing the current input record. The next input record
  832. Xis read and processing starts over with the first pattern in the
  833. XAWK program. If the end of the input data is reached, the
  834. X.B END
  835. Xblock(s), if any, are executed.
  836. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  837. X.B print
  838. Xprints the current record.
  839. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  840. X.BI print " expr-list"
  841. Xprints expressions.
  842. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  843. X.BI print " expr-list" " >" file
  844. Xprints expressions on
  845. X.IR file .
  846. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  847. X.BI printf " fmt, expr-list"
  848. Xformat and print.
  849. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  850. X.BI printf " fmt, expr-list" " >" file
  851. Xformat and print on
  852. X.IR file .
  853. X.TP \l'\fBprintf \fIfmt, expr-list\fR'
  854. X.BI system( cmd-line )
  855. Xexecute the command
  856. X.IR cmd-line ,
  857. Xand return the exit status.
  858. X(This may not be available on 
  859. Xsystems besides \s-1UNIX\s+1 and \s-1GNU\s+1.)
  860. X.RE
  861. X.PP
  862. XOther input/output redirections are also allowed. For
  863. X.B print
  864. Xand
  865. X.BR printf ,
  866. X.BI >> file
  867. Xappends output to the
  868. X.IR file ,
  869. Xwhile
  870. X.BI | " command"
  871. Xwrites on a pipe.
  872. XIn a similar fashion,
  873. X.IB command " | getline"
  874. Xpipes into
  875. X.BR getline .
  876. X.BR Getline
  877. Xwill return 0 on end of file, and \-1 on an error.
  878. X.SS The \fIprintf\fP Statement
  879. X.PP
  880. XThe AWK versions of the
  881. X.B printf
  882. Xand
  883. X.B sprintf
  884. X(see below)
  885. Xfunctions accept the following conversion specification formats:
  886. X.RS
  887. X.TP
  888. X.B %c
  889. XAn ASCII character.
  890. XIf the argument used for
  891. X.B %c
  892. Xis numeric, it is treated as a character and printed.
  893. XOtherwise, the argument is assumed to be a string, and the only first
  894. Xcharacter of that string is printed.
  895. X.TP
  896. X.B %d
  897. XA decimal number (the integer part).
  898. X.TP
  899. X.B %i
  900. XJust like
  901. X.BR %d .
  902. X.TP
  903. X.B %e
  904. XA floating point number of the form
  905. X.BR [\-]d.ddddddE[+\^\-]dd .
  906. X.TP
  907. X.B %f
  908. XA floating point number of the form
  909. X.BR [\-]ddd.dddddd .
  910. X.TP
  911. X.B %g
  912. XUse
  913. X.B e
  914. Xor
  915. X.B f
  916. Xconversion, whichever is shorter, with nonsignificant zeros suppressed.
  917. X.TP
  918. X.B %o
  919. XAn unsigned octal number (again, an integer).
  920. X.TP
  921. X.B %s
  922. XA character string.
  923. X.TP
  924. X.B %x
  925. XAn unsigned hexadecimal number (an integer).
  926. X.TP
  927. X.B %X
  928. XLike
  929. X.BR %x ,
  930. Xbut using
  931. X.B ABCDEF
  932. Xinstead of
  933. X.BR abcdef .
  934. X.TP
  935. X.B %%
  936. XA single
  937. X.B %
  938. Xcharacter; no argument is converted.
  939. X.RE
  940. X.PP
  941. XThere are optional, additional parameters that may lie between the
  942. X.B %
  943. Xand the control letter:
  944. X.RS
  945. X.TP
  946. X.B \-
  947. XThe expression should be left-justified within its field.
  948. X.TP
  949. X.I width
  950. XThe field should be padded to this width. If the number has a leading
  951. Xzero, then the field will be padded with zeros.
  952. XOtherwise it is padded with blanks.
  953. X.TP
  954. X.BI . prec
  955. XA number indicating the maximum width of strings or digits to the right
  956. Xof the decimal point.
  957. X.RE
  958. X.PP
  959. XThe dynamic
  960. X.I width
  961. Xand
  962. X.I prec
  963. Xcapabilities of the C library
  964. X.B printf
  965. Xroutines are not supported.
  966. XHowever, they may be simulated by using
  967. Xthe AWK concatenation operation to build up
  968. Xa format specification dynamically.
  969. X.SS Special File Names
  970. X.PP
  971. XWhen doing I/O redirection from either
  972. X.B print
  973. Xor
  974. X.B printf
  975. Xinto a file,
  976. Xor via
  977. X.B getline
  978. Xfrom a file,
  979. X.I gawk
  980. Xrecognizes certain special filenames internally.  These filenames
  981. Xallow access to open file descriptors inherited from
  982. X.IR gawk 's
  983. Xparent process (usually the shell).  The filenames are:
  984. X.RS
  985. X.TP
  986. X.B /dev/stdin
  987. XThe standard input.
  988. X.TP
  989. X.B /dev/stdout
  990. XThe standard output.
  991. X.TP
  992. X.B /dev/stderr
  993. XThe standard error output.
  994. X.TP
  995. X.BI /dev/fd/\^ n
  996. XThe file denoted by the open file descriptor
  997. X.IR n .
  998. X.RE
  999. X.PP
  1000. XThese are particularly useful for error messages. For example:
  1001. X.PP
  1002. X.RS
  1003. X.ft B
  1004. Xprint "You blew it!" > "/dev/stderr"
  1005. X.ft R
  1006. X.RE
  1007. X.PP
  1008. Xwhereas you would otherwise have to use
  1009. X.PP
  1010. X.RS
  1011. X.ft B
  1012. Xprint "You blew it!" | "cat 1>&2"
  1013. X.ft R
  1014. X.RE
  1015. X.PP
  1016. XThese file names may also be used on the command line to name data files.
  1017. X.SS Numeric Functions
  1018. X.PP
  1019. XAWK has the following pre-defined arithmetic functions:
  1020. X.PP
  1021. X.RS
  1022. X.TP \l'\fBsrand(\fIexpr\fB)\fR'
  1023. X.BI atan2( y , " x" )
  1024. Xreturns the arctangent of
  1025. X.I y/x
  1026. Xin radians.
  1027. X.TP \l'\fBsrand(\fIexpr\fB)\fR'
  1028. X.BI cos( expr )
  1029. Xreturns the cosine in radians.
  1030. X.TP \l'\fBsrand(\fIexpr\fB)\fR'
  1031. X.BI exp( expr )
  1032. Xthe exponential function.
  1033. X.TP \l'\fBsrand(\fIexpr\fB)\fR'
  1034. X.BI int( expr )
  1035. Xtruncates to integer.
  1036. X.TP \l'\fBsrand(\fIexpr\fB)\fR'
  1037. X.BI log( expr )
  1038. Xthe natural logarithm function.
  1039. X.TP \l'\fBsrand(\fIexpr\fB)\fR'
  1040. X.B rand()
  1041. Xreturns a random number between 0 and 1.
  1042. X.TP \l'\fBsrand(\fIexpr\fB)\fR'
  1043. X.BI sin( expr )
  1044. Xreturns the sine in radians.
  1045. X.TP \l'\fBsrand(\fIexpr\fB)\fR'
  1046. X.BI sqrt( expr )
  1047. Xthe square root function.
  1048. X.TP \l'\fBsrand(\fIexpr\fB)\fR'
  1049. X.BI srand( expr )
  1050. Xuse
  1051. X.I expr
  1052. Xas a new seed for the random number generator. If no
  1053. X.I expr
  1054. Xis provided, the time of day will be used.
  1055. XThe return value is the previous seed for the random
  1056. Xnumber generator.
  1057. X.RE
  1058. X.SS String Functions
  1059. X.PP
  1060. XAWK has the following pre-defined string functions:
  1061. X.PP
  1062. X.RS
  1063. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1064. X\fBgsub(\fIr\fB, \fIs\fB, \fIt\fB)\fR
  1065. Xfor each substring matching the regular expression
  1066. X.I r
  1067. Xin the string
  1068. X.IR t ,
  1069. Xsubstitute the string
  1070. X.IR s ,
  1071. Xand return the number of substitutions.
  1072. XIf
  1073. X.I t
  1074. Xis not supplied, use
  1075. X.BR $0 .
  1076. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1077. X.BI index( s , " t" )
  1078. Xreturns the index of the string
  1079. X.I t
  1080. Xin the string
  1081. X.IR s ,
  1082. Xor 0 if
  1083. X.I t
  1084. Xis not present.
  1085. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1086. X.BI length( s )
  1087. Xreturns the length of the string
  1088. X.IR s .
  1089. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1090. X.BI match( s , " r" )
  1091. Xreturns the position in
  1092. X.I s
  1093. Xwhere the regular expression
  1094. X.I r
  1095. Xoccurs, or 0 if
  1096. X.I r
  1097. Xis not present, and sets the values of
  1098. X.B RSTART
  1099. Xand
  1100. X.BR RLENGTH .
  1101. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1102. X\fBsplit(\fIs\fB, \fIa\fB, \fIr\fB)\fR
  1103. Xsplits the string
  1104. X.I s
  1105. Xinto the array
  1106. X.I a
  1107. Xon the regular expression
  1108. X.IR r ,
  1109. Xand returns the number of fields. If
  1110. X.I r
  1111. Xis omitted,
  1112. X.B FS
  1113. Xis used instead.
  1114. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1115. X.BI sprintf( fmt , " expr-list" )
  1116. Xprints
  1117. X.I expr-list
  1118. Xaccording to
  1119. X.IR fmt ,
  1120. Xand returns the resulting string.
  1121. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1122. X\fBsub(\fIr\fB, \fIs\fB, \fIt\fB)\fR
  1123. Xthis is just like
  1124. X.BR gsub ,
  1125. Xbut only the first matching substring is replaced.
  1126. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1127. X\fBsubstr(\fIs\fB, \fIi\fB, \fIn\fB)\fR
  1128. Xreturns the
  1129. X.IR n -character
  1130. Xsubstring of
  1131. X.I s
  1132. Xstarting at
  1133. X.IR i .
  1134. XIf
  1135. X.I n
  1136. Xis omitted, the rest of
  1137. X.I s
  1138. Xis used.
  1139. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1140. X.BI tolower( str )
  1141. Xreturns a copy of the string
  1142. X.IR str ,
  1143. Xwith all the upper-case characters in
  1144. X.I str
  1145. Xtranslated to their corresponding lower-case counterparts.
  1146. XNon-alphabetic characters are left unchanged.
  1147. X.TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR'
  1148. X.BI toupper( str )
  1149. Xreturns a copy of the string
  1150. X.IR str ,
  1151. Xwith all the lower-case characters in
  1152. X.I str
  1153. Xtranslated to their corresponding upper-case counterparts.
  1154. XNon-alphabetic characters are left unchanged.
  1155. X.RE
  1156. X.SS String Constants
  1157. X.PP
  1158. XString constants in AWK are sequences of characters enclosed
  1159. Xbetween double quotes (\fB"\fR). Within strings, certain
  1160. X.I "escape sequences"
  1161. Xare recognized, as in C. These are:
  1162. X.PP
  1163. X.RS
  1164. X.TP \l'\fB\e\fIddd\fR'
  1165. X.B \e\e
  1166. XA literal backslash.
  1167. X.TP \l'\fB\e\fIddd\fR'
  1168. X.B \ea
  1169. XThe ``alert'' character; usually the ASCII BEL character.
  1170. X.TP \l'\fB\e\fIddd\fR'
  1171. X.B \eb
  1172. Xbackspace.
  1173. X.TP \l'\fB\e\fIddd\fR'
  1174. X.B \ef
  1175. Xform-feed.
  1176. X.TP \l'\fB\e\fIddd\fR'
  1177. X.B \en
  1178. Xnew line.
  1179. X.TP \l'\fB\e\fIddd\fR'
  1180. X.B \er
  1181. Xcarriage return.
  1182. X.TP \l'\fB\e\fIddd\fR'
  1183. X.B \et
  1184. Xhorizontal tab.
  1185. X.TP \l'\fB\e\fIddd\fR'
  1186. X.B \ev
  1187. Xvertical tab.
  1188. X.TP \l'\fB\e\fIddd\fR'
  1189. X.BI \ex "\^hex digits"
  1190. XThe character represented by the string of hexadecimal digits following
  1191. Xthe
  1192. X.BR \ex .
  1193. XAs in ANSI C, all following hexadecimal digits are considered part of
  1194. Xthe escape sequence.
  1195. X(This feature should tell us something about language design by committee.)
  1196. XE.g., "\ex1B" is the ASCII ESC (escape) character.
  1197. X.TP \l'\fB\e\fIddd\fR'
  1198. X.BI \e ddd
  1199. XThe character represented by the 1-, 2-, or 3-digit sequence of octal
  1200. Xdigits. E.g. "\e033" is the ASCII ESC (escape) character.
  1201. X.TP \l'\fB\e\fIddd\fR'
  1202. X.BI \e c
  1203. XThe literal character
  1204. X.IR c\^ .
  1205. X.RE
  1206. X.PP
  1207. XThe escape sequences may also be used inside constant regular expressions
  1208. X(e.g.,
  1209. X.B "/[\ \et\ef\en\er\ev]/"
  1210. Xmatches whitespace characters).
  1211. X.SH FUNCTIONS
  1212. XFunctions in AWK are defined as follows:
  1213. X.PP
  1214. X.RS
  1215. X\fBfunction \fIname\fB(\fIparameter list\fB) { \fIstatements \fB}\fR
  1216. X.RE
  1217. X.PP
  1218. XFunctions are executed when called from within the action parts of regular
  1219. Xpattern-action statements. Actual parameters supplied in the function
  1220. Xcall are used to instantiate the formal parameters declared in the function.
  1221. XArrays are passed by reference, other variables are passed by value.
  1222. X.PP
  1223. XSince functions were not originally part of the AWK language, the provision
  1224. Xfor local variables is rather clumsy: they are declared as extra parameters
  1225. Xin the parameter list. The convention is to separate local variables from
  1226. Xreal parameters by extra spaces in the parameter list. For example:
  1227. X.PP
  1228. X.RS
  1229. X.ft B
  1230. X.nf
  1231. Xfunction  f(p, q,     a, b) {    # a & b are local
  1232. X            ..... }
  1233. X
  1234. X/abc/    { ... ; f(1, 2) ; ... }
  1235. X.fi
  1236. X.ft R
  1237. X.RE
  1238. X.PP
  1239. XThe left parenthesis in a function call is required
  1240. Xto immediately follow the function name,
  1241. Xwithout any intervening white space.
  1242. XThis is to avoid a syntactic ambiguity with the concatenation operator.
  1243. XThis restriction does not apply to the built-in functions listed above.
  1244. X.PP
  1245. XFunctions may call each other and may be recursive.
  1246. XFunction parameters used as local variables are initialized
  1247. Xto the null string and the number zero upon function invocation.
  1248. X.PP
  1249. XThe word
  1250. X.B func
  1251. Xmay be used in place of
  1252. X.BR function .
  1253. X.SH EXAMPLES
  1254. X.nf
  1255. XPrint and sort the login names of all users:
  1256. X
  1257. X.ft B
  1258. X    BEGIN    { FS = ":" }
  1259. X        { print $1 | "sort" }
  1260. X
  1261. X.ft R
  1262. XCount lines in a file:
  1263. X
  1264. X.ft B
  1265. X        { nlines++ }
  1266. X    END    { print nlines }
  1267. X
  1268. X.ft R
  1269. XPrecede each line by its number in the file:
  1270. X
  1271. X.ft B
  1272. X    { print FNR, $0 }
  1273. X
  1274. X.ft R
  1275. XConcatenate and line number (a variation on a theme):
  1276. X
  1277. X.ft B
  1278. X    { print NR, $0 }
  1279. X.ft R
  1280. X.fi
  1281. X.SH SEE ALSO
  1282. X.IR egrep (1)
  1283. X.PP
  1284. X.IR "The AWK Programming Language" ,
  1285. XAlfred V. Aho, Brian W. Kernighan, Peter J. Weinberger,
  1286. XAddison-Wesley, 1988. ISBN 0-201-07981-X.
  1287. X.PP
  1288. X.IR "The GAWK Manual" ,
  1289. Xpublished by the Free Software Foundation, 1989.
  1290. X.SH SYSTEM V RELEASE 4 COMPATIBILITY
  1291. XA primary goal for
  1292. X.I gawk
  1293. Xis compatibility with the latest version of \s-1UNIX\s+1
  1294. X.IR awk .
  1295. XTo this end,
  1296. X.I gawk
  1297. Xincorporates the following user visible
  1298. Xfeatures which are not described in the AWK book,
  1299. Xbut are part of
  1300. X.I awk
  1301. Xin System V Release 4.
  1302. X.PP
  1303. XThe
  1304. X.B \-v
  1305. Xoption for assigning variables before program execution starts is new.
  1306. XThe book indicates that command line variable assignment happens when
  1307. X.I awk
  1308. Xwould otherwise open the argument as a file, which is after the
  1309. X.B BEGIN
  1310. Xblock is executed.  However, in earlier implementations, when such an
  1311. Xassignment appeared before any file names, the assignment would happen
  1312. X.I before
  1313. Xthe
  1314. X.B BEGIN
  1315. Xblock was run.  Applications came to depend on this ``feature.''
  1316. XWhen
  1317. X.I awk
  1318. Xwas changed to match its documentation, this option was added to
  1319. Xaccomodate applications that depended upon the old behaviour.
  1320. X.PP
  1321. XWhen processing arguments,
  1322. X.I gawk
  1323. Xuses the special option ``\fB\-\^\-\fP'' to signal the end of
  1324. Xarguments, and warns about, but otherwise ignores, undefined options.
  1325. X.PP
  1326. XThe AWK book does not define the return value of
  1327. X.BR srand() .
  1328. XThe System V Release 4 version of \s-1UNIX\s+1
  1329. X.I awk
  1330. Xhas it return the seed it was using, to allow keeping track
  1331. Xof random number sequences. Therefore
  1332. X.B srand()
  1333. Xin
  1334. X.I gawk
  1335. Xalso returns its current seed.
  1336. X.PP
  1337. XOther new features are:
  1338. XThe use of multiple
  1339. X.B \-f
  1340. Xoptions; the
  1341. X.B ENVIRON
  1342. Xarray; the
  1343. X.BR \ea ,
  1344. Xand
  1345. X.BR \ev ,
  1346. X.B \ex
  1347. Xescape sequences; the
  1348. X.B tolower
  1349. Xand
  1350. X.B toupper
  1351. Xbuilt-in functions; and the ANSI C conversion specifications in
  1352. X.BR printf .
  1353. X.SH GNU EXTENSIONS
  1354. X.I Gawk
  1355. Xhas some extensions to System V
  1356. X.IR awk .
  1357. XThey are described in this section.  All the extensions described here
  1358. Xcan be disabled by compiling
  1359. X.I gawk
  1360. Xwith
  1361. X.BR \-DSTRICT ,
  1362. Xor by invoking
  1363. X.I gawk
  1364. Xwith the
  1365. X.B \-c
  1366. Xoption.
  1367. XIf the underlying operating system supports the
  1368. X.B /dev/fd
  1369. Xdirectory and corresponding files, then
  1370. X.I gawk
  1371. Xcan be compiled with
  1372. X.B \-DNO_DEV_FD
  1373. Xto disable the special filename processing.
  1374. X.PP
  1375. XThe following features of
  1376. X.I gawk
  1377. Xare not available in
  1378. XSystem V
  1379. X.IR awk .
  1380. X.RS
  1381. X.TP \l'\(bu'
  1382. X\(bu
  1383. XThe special file names available for I/O redirection are not recognized.
  1384. X.TP \l'\(bu'
  1385. X\(bu
  1386. XThe
  1387. X.B IGNORECASE
  1388. Xvariable and its side-effects are not available.
  1389. X.TP \l'\(bu'
  1390. X\(bu
  1391. XNo path search is performed for files named via the
  1392. X.B \-f
  1393. Xoption.  Therefore the
  1394. X.B AWKPATH
  1395. Xenvironment variable is not special.
  1396. X.TP \l'\(bu'
  1397. X\(bu
  1398. XThe
  1399. X.BR \-a ,
  1400. X.BR \-e ,
  1401. X.BR \-c ,
  1402. X.BR \-C ,
  1403. Xand
  1404. X.B \-V
  1405. Xcommand line options.
  1406. X.RE
  1407. X.PP
  1408. XThe AWK book does not define the return value of the
  1409. X.B close
  1410. Xfunction.
  1411. X.IR Gawk\^ 's
  1412. X.B close
  1413. Xreturns the value from
  1414. X.IR fclose (3),
  1415. Xor
  1416. X.IR pclose (3),
  1417. Xwhen closing a file or pipe, respectively.
  1418. X.PP
  1419. XWhen
  1420. X.I gawk
  1421. Xis invoked with the
  1422. X.B \-c
  1423. Xoption,
  1424. Xif the
  1425. X.I fs
  1426. Xargument to the
  1427. X.B \-F
  1428. Xoption is ``t'', then
  1429. X.B FS
  1430. Xwill be set to the tab character.
  1431. XSince this is a rather ugly special case, it is not the default behavior.
  1432. X.ig
  1433. X.PP
  1434. XThe rest of the features described in this section may change at some time in
  1435. Xthe future, or may go away entirely.
  1436. XYou should not write programs that depend upon them.
  1437. X.PP
  1438. X.I Gawk
  1439. Xaccepts the following additional options:
  1440. X.TP
  1441. X.B \-D
  1442. XTurn on general debugging and turn on
  1443. X.IR yacc (1)
  1444. Xor
  1445. X.IR bison (1)
  1446. Xdebugging output during program parsing.
  1447. XThis option should only be of interest to the
  1448. X.I gawk
  1449. Xmaintainers, and may not even be compiled into
  1450. X.IR gawk .
  1451. X.TP
  1452. X.B \-d
  1453. XTurn on general debugging and print the
  1454. X.I gawk
  1455. Xinternal tree as the program is executed.
  1456. XThis option should only be of interest to the
  1457. X.I gawk
  1458. Xmaintainers, and may not even be compiled into
  1459. X.IR gawk .
  1460. X..
  1461. X.SH BUGS
  1462. XThe
  1463. X.B \-F
  1464. Xoption is not necessary given the command line variable assignment feature;
  1465. Xit remains only for backwards compatibility.
  1466. X.PP
  1467. XThere are now too many options.
  1468. XFortunately, most of them are rarely needed.
  1469. X.SH AUTHORS
  1470. XThe original version of \s-1UNIX\s+1
  1471. X.I awk
  1472. Xwas designed and implemented by Alfred Aho,
  1473. XPeter Weinberger, and Brian Kernighan of AT&T Bell Labs. Brian Kernighan
  1474. Xcontinues to maintain and enhance it.
  1475. X.PP
  1476. XPaul Rubin and Jay Fenlason,
  1477. Xof the Free Software Foundation, wrote
  1478. X.IR gawk ,
  1479. Xto be compatible with the original version of
  1480. X.I awk
  1481. Xdistributed in Seventh Edition \s-1UNIX\s+1.
  1482. XJohn Woods contributed a number of bug fixes.
  1483. XDavid Trueman of Dalhousie University, with contributions
  1484. Xfrom Arnold Robbins at Emory University, made
  1485. X.I gawk
  1486. Xcompatible with the new version of \s-1UNIX\s+1
  1487. X.IR awk .
  1488. X.SH ACKNOWLEDGEMENTS
  1489. XBrian Kernighan of Bell Labs
  1490. Xprovided valuable assistance during testing and debugging.
  1491. XWe thank him.
  1492. END_OF_FILE
  1493.   if test 33549 -ne `wc -c <'./gawk.1'`; then
  1494.     echo shar: \"'./gawk.1'\" unpacked with wrong size!
  1495.   fi
  1496.   # end of './gawk.1'
  1497. fi
  1498. if test -f './io.c' -a "${1}" != "-c" ; then 
  1499.   echo shar: Will not clobber existing file \"'./io.c'\"
  1500. else
  1501.   echo shar: Extracting \"'./io.c'\" \(17467 characters\)
  1502.   sed "s/^X//" >'./io.c' <<'END_OF_FILE'
  1503. X/*
  1504. X * io.c - routines for dealing with input and output and records
  1505. X */
  1506. X
  1507. X/* 
  1508. X * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
  1509. X * 
  1510. X * This file is part of GAWK, the GNU implementation of the
  1511. X * AWK Progamming Language.
  1512. X * 
  1513. X * GAWK is free software; you can redistribute it and/or modify
  1514. X * it under the terms of the GNU General Public License as published by
  1515. X * the Free Software Foundation; either version 1, or (at your option)
  1516. X * any later version.
  1517. X * 
  1518. X * GAWK is distributed in the hope that it will be useful,
  1519. X * but WITHOUT ANY WARRANTY; without even the implied warranty of
  1520. X * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  1521. X * GNU General Public License for more details.
  1522. X * 
  1523. X * You should have received a copy of the GNU General Public License
  1524. X * along with GAWK; see the file COPYING.  If not, write to
  1525. X * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  1526. X */
  1527. X
  1528. X#include "awk.h"
  1529. X#ifndef O_RDONLY
  1530. X#include <fcntl.h>
  1531. X#endif
  1532. X#include <signal.h>
  1533. X
  1534. Xextern FILE *popen();
  1535. X
  1536. Xstatic void do_file();
  1537. Xstatic IOBUF *nextfile();
  1538. Xstatic int get_a_record();
  1539. Xstatic int iop_close();
  1540. Xstatic IOBUF *iop_alloc();
  1541. Xstatic void close_one();
  1542. Xstatic int close_redir();
  1543. Xstatic IOBUF *gawk_popen();
  1544. Xstatic int gawk_pclose();
  1545. X
  1546. Xstatic struct redirect *red_head = NULL;
  1547. Xstatic int getline_redirect = 0;    /* "getline <file" being executed */
  1548. X
  1549. Xextern char *line_buf;
  1550. Xextern int output_is_tty;
  1551. Xextern NODE *ARGC_node;
  1552. Xextern NODE *ARGV_node;
  1553. Xextern NODE **fields_arr;
  1554. X
  1555. Xint field_num;
  1556. X
  1557. Xstatic IOBUF *
  1558. Xnextfile()
  1559. X{
  1560. X    static int i = 1;
  1561. X    static int files = 0;
  1562. X    static IOBUF *curfile = NULL;
  1563. X    char *arg;
  1564. X    char *cp;
  1565. X    int fd = -1;
  1566. X
  1567. X    if (curfile != NULL && curfile->cnt != EOF)
  1568. X        return curfile;
  1569. X    for (; i < (int) (ARGC_node->lnode->numbr); i++) {
  1570. X        arg = (*assoc_lookup(ARGV_node, tmp_number((AWKNUM) i)))->stptr;
  1571. X        if (*arg == '\0')
  1572. X            continue;
  1573. X        cp = strchr(arg, '=');
  1574. X        if (cp != NULL) {
  1575. X            *cp++ = '\0';
  1576. X            variable(arg)->var_value = make_string(cp, strlen(cp));
  1577. X            *--cp = '=';    /* restore original text of ARGV */
  1578. X        } else {
  1579. X            files++;
  1580. X            if (STREQ(arg, "-"))
  1581. X                fd = 0;
  1582. X            else
  1583. X                fd = devopen(arg, "r");
  1584. X            if (fd == -1)
  1585. X                fatal("cannot open file `%s' for reading (%s)",
  1586. X                    arg, strerror(errno));
  1587. X                /* NOTREACHED */
  1588. X            /* This is a kludge.  */
  1589. X            deref = FILENAME_node->var_value;
  1590. X            do_deref();
  1591. X            FILENAME_node->var_value =
  1592. X                make_string(arg, strlen(arg));
  1593. X            FNR_node->var_value->numbr = 0.0;
  1594. X            i++;
  1595. X            break;
  1596. X        }
  1597. X    }
  1598. X    if (files == 0) {
  1599. X        files++;
  1600. X        /* no args. -- use stdin */
  1601. X        /* FILENAME is init'ed to "-" */
  1602. X        /* FNR is init'ed to 0 */
  1603. X        fd = 0;
  1604. X    }
  1605. X    if (fd == -1)
  1606. X        return NULL;
  1607. X    return curfile = iop_alloc(fd);
  1608. X}
  1609. X
  1610. Xstatic IOBUF *
  1611. Xiop_alloc(fd)
  1612. Xint fd;
  1613. X{
  1614. X    IOBUF *iop;
  1615. X    struct stat stb;
  1616. X
  1617. X    /*
  1618. X     * System V doesn't have the file system block size in the
  1619. X     * stat structure. So we have to make some sort of reasonable
  1620. X     * guess. We use stdio's BUFSIZ, since that is what it was
  1621. X     * meant for in the first place.
  1622. X     */
  1623. X#ifdef BLKSIZE_MISSING
  1624. X#define    DEFBLKSIZE    BUFSIZ
  1625. X#else
  1626. X#define DEFBLKSIZE    (stb.st_blksize ? stb.st_blksize : BUFSIZ)
  1627. X#endif
  1628. X
  1629. X    if (fd == -1)
  1630. X        return NULL;
  1631. X    emalloc(iop, IOBUF *, sizeof(IOBUF), "nextfile");
  1632. X    iop->flag = 0;
  1633. X    if (isatty(fd)) {
  1634. X        iop->flag |= IOP_IS_TTY;
  1635. X        iop->size = BUFSIZ;
  1636. X    } else if (fstat(fd, &stb) == -1)
  1637. X        fatal("can't stat fd %d (%s)", fd, strerror(errno));
  1638. X    else if (lseek(fd, 0L, 0) == -1)
  1639. X        iop->size = DEFBLKSIZE;
  1640. X    else
  1641. X        iop->size = (stb.st_size < DEFBLKSIZE ?
  1642. X                stb.st_size+1 : DEFBLKSIZE);
  1643. X    errno = 0;
  1644. X    iop->fd = fd;
  1645. X    emalloc(iop->buf, char *, iop->size, "nextfile");
  1646. X    iop->off = iop->buf;
  1647. X    iop->cnt = 0;
  1648. X    iop->secsiz = iop->size < BUFSIZ ? iop->size : BUFSIZ;
  1649. X    emalloc(iop->secbuf, char *, iop->secsiz, "nextfile");
  1650. X    return iop;
  1651. X}
  1652. X
  1653. Xvoid
  1654. Xdo_input()
  1655. X{
  1656. X    IOBUF *iop;
  1657. X    extern int exiting;
  1658. X
  1659. X    while ((iop = nextfile()) != NULL) {
  1660. X        do_file(iop);
  1661. X        if (exiting)
  1662. X            break;
  1663. X    }
  1664. X}
  1665. X
  1666. Xstatic int
  1667. Xiop_close(iop)
  1668. XIOBUF *iop;
  1669. X{
  1670. X    int ret;
  1671. X
  1672. X    ret = close(iop->fd);
  1673. X    if (ret == -1)
  1674. X        warning("close of fd %d failed (%s)", iop->fd, strerror(errno));
  1675. X    free(iop->buf);
  1676. X    free(iop->secbuf);
  1677. X    free((char *)iop);
  1678. X    return ret == -1 ? 1 : 0;
  1679. X}
  1680. X
  1681. X/*
  1682. X * This reads in a record from the input file
  1683. X */
  1684. Xstatic int
  1685. Xinrec(iop)
  1686. XIOBUF *iop;
  1687. X{
  1688. X    int cnt;
  1689. X    int retval = 0;
  1690. X
  1691. X    cnt = get_a_record(&line_buf, iop);
  1692. X    if (cnt == EOF) {
  1693. X        cnt = 0;
  1694. X        retval = 1;
  1695. X    } else {
  1696. X        if (!getline_redirect) {
  1697. X            assign_number(&NR_node->var_value,
  1698. X                NR_node->var_value->numbr + 1.0);
  1699. X            assign_number(&FNR_node->var_value,
  1700. X                FNR_node->var_value->numbr + 1.0);
  1701. X        }
  1702. X    }
  1703. X    set_record(line_buf, cnt);
  1704. X
  1705. X    return retval;
  1706. X}
  1707. X
  1708. Xstatic void
  1709. Xdo_file(iop)
  1710. XIOBUF *iop;
  1711. X{
  1712. X    /* This is where it spends all its time.  The infamous MAIN LOOP */
  1713. X    if (inrec(iop) == 0)
  1714. X        while (interpret(expression_value) && inrec(iop) == 0)
  1715. X            ;
  1716. X    (void) iop_close(iop);
  1717. X}
  1718. X
  1719. Xint
  1720. Xget_rs()
  1721. X{
  1722. X    register NODE *tmp;
  1723. X
  1724. X    tmp = force_string(RS_node->var_value);
  1725. X    if (tmp->stlen == 0)
  1726. X        return 0;
  1727. X    return *(tmp->stptr);
  1728. X}
  1729. X
  1730. X/* Redirection for printf and print commands */
  1731. Xstruct redirect *
  1732. Xredirect(tree, errflg)
  1733. XNODE *tree;
  1734. Xint *errflg;
  1735. X{
  1736. X    register NODE *tmp;
  1737. X    register struct redirect *rp;
  1738. X    register char *str;
  1739. X    int tflag = 0;
  1740. X    int outflag = 0;
  1741. X    char *direction = "to";
  1742. X    char *mode;
  1743. X    int fd;
  1744. X
  1745. X    switch (tree->type) {
  1746. X    case Node_redirect_append:
  1747. X        tflag = RED_APPEND;
  1748. X    case Node_redirect_output:
  1749. X        outflag = (RED_FILE|RED_WRITE);
  1750. X        tflag |= outflag;
  1751. X        break;
  1752. X    case Node_redirect_pipe:
  1753. X        tflag = (RED_PIPE|RED_WRITE);
  1754. X        break;
  1755. X    case Node_redirect_pipein:
  1756. X        tflag = (RED_PIPE|RED_READ);
  1757. X        break;
  1758. X    case Node_redirect_input:
  1759. X        tflag = (RED_FILE|RED_READ);
  1760. X        break;
  1761. X    default:
  1762. X        fatal ("invalid tree type %d in redirect()", tree->type);
  1763. X        break;
  1764. X    }
  1765. X    tmp = force_string(tree_eval(tree->subnode));
  1766. X    str = tmp->stptr;
  1767. X    for (rp = red_head; rp != NULL; rp = rp->next)
  1768. X        if (STREQ(rp->value, str)
  1769. X            && ((rp->flag & ~RED_NOBUF) == tflag
  1770. X            || (outflag
  1771. X                && (rp->flag & (RED_FILE|RED_WRITE)) == outflag)))
  1772. X            break;
  1773. X    if (rp == NULL) {
  1774. X        emalloc(rp, struct redirect *, sizeof(struct redirect),
  1775. X            "redirect");
  1776. X        emalloc(str, char *, tmp->stlen+1, "redirect");
  1777. X        memcpy(str, tmp->stptr, tmp->stlen+1);
  1778. X        rp->value = str;
  1779. X        rp->flag = tflag;
  1780. X        rp->offset = 0;
  1781. X        rp->fp = NULL;
  1782. X        rp->iop = NULL;
  1783. X        /* maintain list in most-recently-used first order */
  1784. X        if (red_head)
  1785. X            red_head->prev = rp;
  1786. X        rp->prev = NULL;
  1787. X        rp->next = red_head;
  1788. X        red_head = rp;
  1789. X    }
  1790. X    while (rp->fp == NULL && rp->iop == NULL) {
  1791. X        mode = NULL;
  1792. X        errno = 0;
  1793. X        switch (tree->type) {
  1794. X        case Node_redirect_output:
  1795. X            mode = "w";
  1796. X            break;
  1797. X        case Node_redirect_append:
  1798. X            mode = "a";
  1799. X            break;
  1800. X        case Node_redirect_pipe:
  1801. X            if ((rp->fp = popen(str, "w")) == NULL)
  1802. X                fatal("can't open pipe (\"%s\") for output (%s)",
  1803. X                    str, strerror(errno));
  1804. X            rp->flag |= RED_NOBUF;
  1805. X            break;
  1806. X        case Node_redirect_pipein:
  1807. X            direction = "from";
  1808. X            if (gawk_popen(str, rp) == NULL)
  1809. X                fatal("can't open pipe (\"%s\") for input (%s)",
  1810. X                    str, strerror(errno));
  1811. X            break;
  1812. X        case Node_redirect_input:
  1813. X            direction = "from";
  1814. X            rp->iop = iop_alloc(devopen(str, "r"));
  1815. X            break;
  1816. X        default:
  1817. X            cant_happen();
  1818. X        }
  1819. X        if (mode != NULL) {
  1820. X            fd = devopen(str, mode);
  1821. X            if (fd != -1) {
  1822. X                rp->fp = fdopen(fd, mode);
  1823. X                if (isatty(fd))
  1824. X                    rp->flag |= RED_NOBUF;
  1825. X            }
  1826. X        }
  1827. X        if (rp->fp == NULL && rp->iop == NULL) {
  1828. X            /* too many files open -- close one and try again */
  1829. X            if (errno == ENFILE || errno == EMFILE)
  1830. X                close_one();
  1831. X            else {
  1832. X                /*
  1833. X                 * Some other reason for failure.
  1834. X                 *
  1835. X                 * On redirection of input from a file,
  1836. X                 * just return an error, so e.g. getline
  1837. X                 * can return -1.  For output to file,
  1838. X                 * complain. The shell will complain on
  1839. X                 * a bad command to a pipe.
  1840. X                 */
  1841. X                *errflg = 1;
  1842. X                if (tree->type == Node_redirect_output
  1843. X                    || tree->type == Node_redirect_append)
  1844. X                    fatal("can't redirect %s `%s' (%s)",
  1845. X                        direction, str, strerror(errno));
  1846. X                else
  1847. X                    return NULL;
  1848. X            }
  1849. X        }
  1850. X    }
  1851. X    if (rp->offset != 0)    /* this file was previously open */
  1852. X        if (fseek(rp->fp, rp->offset, 0) == -1)
  1853. X            fatal("can't seek to %ld on `%s' (%s)",
  1854. X                rp->offset, str, strerror(errno));
  1855. X    free_temp(tmp);
  1856. X    return rp;
  1857. X}
  1858. X
  1859. Xstatic void
  1860. Xclose_one()
  1861. X{
  1862. X    register struct redirect *rp;
  1863. X    register struct redirect *rplast = NULL;
  1864. X
  1865. X    /* go to end of list first, to pick up least recently used entry */
  1866. X    for (rp = red_head; rp != NULL; rp = rp->next)
  1867. X        rplast = rp;
  1868. X    /* now work back up through the list */
  1869. X    for (rp = rplast; rp != NULL; rp = rp->prev)
  1870. X        if (rp->fp && (rp->flag & RED_FILE)) {
  1871. X            rp->offset = ftell(rp->fp);
  1872. X            if (fclose(rp->fp))
  1873. X                warning("close of \"%s\" failed (%s).",
  1874. X                    rp->value, strerror(errno));
  1875. X            rp->fp = NULL;
  1876. X            break;
  1877. X        }
  1878. X    if (rp == NULL)
  1879. X        /* surely this is the only reason ??? */
  1880. X        fatal("too many pipes or input files open"); 
  1881. X}
  1882. X
  1883. XNODE *
  1884. Xdo_close(tree)
  1885. XNODE *tree;
  1886. X{
  1887. X    NODE *tmp;
  1888. X    register struct redirect *rp;
  1889. X
  1890. X    tmp = force_string(tree_eval(tree->subnode));
  1891. X    for (rp = red_head; rp != NULL; rp = rp->next) {
  1892. X        if (STREQ(rp->value, tmp->stptr))
  1893. X            break;
  1894. X    }
  1895. X    free_temp(tmp);
  1896. X    if (rp == NULL) /* no match */
  1897. X        return tmp_number((AWKNUM) 0.0);
  1898. X    fflush(stdout);    /* synchronize regular output */
  1899. X    return tmp_number((AWKNUM)close_redir(rp));
  1900. X}
  1901. X
  1902. Xstatic int
  1903. Xclose_redir(rp)
  1904. Xregister struct redirect *rp;
  1905. X{
  1906. X    int status = 0;
  1907. X
  1908. X    if ((rp->flag & (RED_PIPE|RED_WRITE)) == (RED_PIPE|RED_WRITE))
  1909. X        status = pclose(rp->fp);
  1910. X    else if (rp->fp)
  1911. X        status = fclose(rp->fp);
  1912. X    else if (rp->iop) {
  1913. X        if (rp->flag & RED_PIPE)
  1914. X            status = gawk_pclose(rp);
  1915. X        else
  1916. X            status = iop_close(rp->iop);
  1917. X
  1918. X    }
  1919. X    /* SVR4 awk checks and warns about status of close */
  1920. X    if (status)
  1921. X        warning("failure status (%d) on %s close of \"%s\" (%s).",
  1922. X            status,
  1923. X            (rp->flag & RED_PIPE) ? "pipe" :
  1924. X            "file", rp->value, strerror(errno));
  1925. X    if (rp->next)
  1926. X        rp->next->prev = rp->prev;
  1927. X    if (rp->prev)
  1928. X        rp->prev->next = rp->next;
  1929. X    else
  1930. X        red_head = rp->next;
  1931. X    free(rp->value);
  1932. X    free((char *)rp);
  1933. X    return status;
  1934. X}
  1935. X
  1936. Xint
  1937. Xflush_io ()
  1938. X{
  1939. X    register struct redirect *rp;
  1940. X    int status = 0;
  1941. X
  1942. X    errno = 0;
  1943. X    if (fflush(stdout)) {
  1944. X        warning("error writing standard output (%s).", strerror(errno));
  1945. X        status++;
  1946. X    }
  1947. X    errno = 0;
  1948. X    if (fflush(stderr)) {
  1949. X        warning("error writing standard error (%s).", strerror(errno));
  1950. X        status++;
  1951. X    }
  1952. X    for (rp = red_head; rp != NULL; rp = rp->next)
  1953. X        /* flush both files and pipes, what the heck */
  1954. X        if ((rp->flag & RED_WRITE) && rp->fp != NULL)
  1955. X            if (fflush(rp->fp)) {
  1956. X                warning("%s flush of \"%s\" failed (%s).",
  1957. X                    (rp->flag  & RED_PIPE) ? "pipe" :
  1958. X                    "file", rp->value, strerror(errno));
  1959. X                status++;
  1960. X            }
  1961. X    return status;
  1962. X}
  1963. X
  1964. Xint
  1965. Xclose_io ()
  1966. X{
  1967. X    register struct redirect *rp;
  1968. X    int status = 0;
  1969. X
  1970. X    for (rp = red_head; rp != NULL; rp = rp->next)
  1971. X        if (close_redir(rp))
  1972. X            status++;
  1973. X    return status;
  1974. X}
  1975. X
  1976. X/* devopen --- handle /dev/std{in,out,err}, /dev/fd/N, regular files */
  1977. Xint
  1978. Xdevopen (name, mode)
  1979. Xchar *name, *mode;
  1980. X{
  1981. X    int openfd = -1;
  1982. X    FILE *fdopen ();
  1983. X    char *cp;
  1984. X    int flag = 0;
  1985. X
  1986. X    switch(mode[0]) {
  1987. X    case 'r':
  1988. X        flag = O_RDONLY;
  1989. X        break;
  1990. X
  1991. X    case 'w':
  1992. X        flag = O_WRONLY|O_CREAT|O_TRUNC;
  1993. X        break;
  1994. X
  1995. X    case 'a':
  1996. X        flag = O_WRONLY|O_APPEND|O_CREAT;
  1997. X        break;
  1998. X    default:
  1999. X        cant_happen();
  2000. X    }
  2001. X
  2002. X#if defined(STRICT) || defined(NO_DEV_FD)
  2003. X    return (open (name, flag, 0666));
  2004. X#else
  2005. X    if (strict)
  2006. X        return (open (name, flag, 0666));
  2007. X
  2008. X    if (!STREQN (name, "/dev/", 5))
  2009. X        return (open (name, flag, 0666));
  2010. X    else
  2011. X        cp = name + 5;
  2012. X        
  2013. X    /* XXX - first three tests ignore mode */
  2014. X    if (STREQ(cp, "stdin"))
  2015. X        return (0);
  2016. X    else if (STREQ(cp, "stdout"))
  2017. X        return (1);
  2018. X    else if (STREQ(cp, "stderr"))
  2019. X        return (2);
  2020. X    else if (STREQN(cp, "fd/", 3)) {
  2021. X        cp += 3;
  2022. X        if (sscanf (cp, "%d", & openfd) == 1 && openfd >= 0)
  2023. X            /* got something */
  2024. X            return openfd;
  2025. X        else
  2026. X            return -1;
  2027. X    } else
  2028. X        return (open (name, flag, 0666));
  2029. X#endif
  2030. X}
  2031. X
  2032. X#ifndef MSDOS
  2033. Xstatic IOBUF *
  2034. Xgawk_popen(cmd, rp)
  2035. Xchar *cmd;
  2036. Xstruct redirect *rp;
  2037. X{
  2038. X    int p[2];
  2039. X    register int pid;
  2040. X
  2041. X    rp->pid = -1;
  2042. X    rp->iop = NULL;
  2043. X    if (pipe(p) < 0)
  2044. X        return NULL;
  2045. X    if ((pid = fork()) == 0) {
  2046. X        close(p[0]);
  2047. X        dup2(p[1], 1);
  2048. X        close(p[1]);
  2049. X        execl("/bin/sh", "sh", "-c", cmd, 0);
  2050. X        _exit(127);
  2051. X    }
  2052. X    if (pid == -1)
  2053. X        return NULL;
  2054. X    rp->pid = pid;
  2055. X    close(p[1]);
  2056. X    return (rp->iop = iop_alloc(p[0]));
  2057. X}
  2058. X
  2059. Xstatic int
  2060. Xgawk_pclose(rp)
  2061. Xstruct redirect *rp;
  2062. X{
  2063. X    SIGTYPE (*hstat)(), (*istat)(), (*qstat)();
  2064. X    int pid;
  2065. X    int status;
  2066. X    struct redirect *redp;
  2067. X
  2068. X    iop_close(rp->iop);
  2069. X    if (rp->pid == -1)
  2070. X        return rp->status;
  2071. X    hstat = signal(SIGHUP, SIG_IGN);
  2072. X    istat = signal(SIGINT, SIG_IGN);
  2073. X    qstat = signal(SIGQUIT, SIG_IGN);
  2074. X    for (;;) {
  2075. X        pid = wait(&status);
  2076. X        if (pid == -1 && errno == ECHILD)
  2077. X            break;
  2078. X        else if (pid == rp->pid) {
  2079. X            rp->pid = -1;
  2080. X            rp->status = status;
  2081. X            break;
  2082. X        } else {
  2083. X            for (redp = red_head; redp != NULL; redp = redp->next)
  2084. X                if (pid == redp->pid) {
  2085. X                    redp->pid = -1;
  2086. X                    redp->status = status;
  2087. X                    break;
  2088. X                }
  2089. X        }
  2090. X    }
  2091. X    signal(SIGHUP, hstat);
  2092. X    signal(SIGINT, istat);
  2093. X    signal(SIGQUIT, qstat);
  2094. X    return(rp->status);
  2095. X}
  2096. X#else
  2097. Xstatic
  2098. Xstruct {
  2099. X    char *command;
  2100. X    char *name;
  2101. X} pipes[_NFILE];
  2102. X
  2103. Xstatic IOBUF *
  2104. Xgawk_popen(cmd, rp)
  2105. Xchar *cmd;
  2106. Xstruct redirect *rp;
  2107. X{
  2108. X    extern char *strdup(const char *);
  2109. X    int current;
  2110. X    char *name;
  2111. X    static char cmdbuf[256];
  2112. X
  2113. X    /* get a name to use.  */
  2114. X    if ((name = tempnam(".", "pip")) == NULL)
  2115. X        return NULL;
  2116. X    sprintf(cmdbuf,"%s > %s", cmd, name);
  2117. X    system(cmdbuf);
  2118. X    if ((current = open(name,O_RDONLY)) == -1)
  2119. X        return NULL;
  2120. X    pipes[current].name = name;
  2121. X    pipes[current].command = strdup(cmd);
  2122. X    return (rp->iop = iop_alloc(current));
  2123. X}
  2124. X
  2125. Xstatic int
  2126. Xgawk_pclose(rp)
  2127. Xstruct redirect *rp;
  2128. X{
  2129. X    int cur = rp->iop->fd;
  2130. X    int rval;
  2131. X
  2132. X    rval = iop_close(rp->iop);
  2133. X
  2134. X    /* check for an open file  */
  2135. X    if (pipes[cur].name == NULL)
  2136. X        return -1;
  2137. X    unlink(pipes[cur].name);
  2138. X    free(pipes[cur].name);
  2139. X    pipes[cur].name = NULL;
  2140. X    free(pipes[cur].command);
  2141. X    return rval;
  2142. X}
  2143. X#endif
  2144. X
  2145. X#define    DO_END_OF_BUF    len = bp - iop->off;\
  2146. X            used = last - start;\
  2147. X            while (len + used > iop->secsiz) {\
  2148. X                iop->secsiz *= 2;\
  2149. X                erealloc(iop->secbuf,char *,iop->secsiz,"get");\
  2150. X            }\
  2151. X            last = iop->secbuf + used;\
  2152. X            start = iop->secbuf;\
  2153. X            memcpy(last, iop->off, len);\
  2154. X            last += len;\
  2155. X            iop->cnt = read(iop->fd, iop->buf, iop->size);\
  2156. X            if (iop->cnt < 0)\
  2157. X                return iop->cnt;\
  2158. X            end_data = iop->buf + iop->cnt;\
  2159. X            iop->off = bp = iop->buf;
  2160. X
  2161. X#define    DO_END_OF_DATA    iop->cnt = read(iop->fd, end_data, end_buf - end_data);\
  2162. X            if (iop->cnt < 0)\
  2163. X                return iop->cnt;\
  2164. X            end_data += iop->cnt;\
  2165. X            if (iop->cnt == 0)\
  2166. X                break;\
  2167. X            iop->cnt = end_data - iop->buf;
  2168. X
  2169. Xstatic int
  2170. Xget_a_record(res, iop)
  2171. Xchar **res;
  2172. XIOBUF *iop;
  2173. X{
  2174. X    register char *end_data;
  2175. X    register char *end_buf;
  2176. X    char *start;
  2177. X    register char *bp;
  2178. X    register char *last;
  2179. X    int len, used;
  2180. X    register char rs = get_rs();
  2181. X
  2182. X    if (iop->cnt < 0)
  2183. X        return iop->cnt;
  2184. X    if ((iop->flag & IOP_IS_TTY) && output_is_tty)
  2185. X        fflush(stdout);
  2186. X    end_data = iop->buf + iop->cnt;
  2187. X    if (iop->off >= end_data) {
  2188. X        iop->cnt = read(iop->fd, iop->buf, iop->size);
  2189. X        if (iop->cnt <= 0)
  2190. X            return iop->cnt = EOF;
  2191. X        end_data = iop->buf + iop->cnt;
  2192. X        iop->off = iop->buf;
  2193. X    }
  2194. X    last = start = bp = iop->off;
  2195. X    end_buf = iop->buf + iop->size;
  2196. X    if (rs == 0) {
  2197. X        while (!(*bp == '\n' && bp != iop->buf && bp[-1] == '\n')) {
  2198. X            if (++bp == end_buf) {
  2199. X                DO_END_OF_BUF
  2200. X            }
  2201. X            if (bp == end_data) {
  2202. X                DO_END_OF_DATA
  2203. X            }
  2204. X        }
  2205. X        if (*bp == '\n' && bp != iop->off && bp[-1] == '\n') {
  2206. X            int tmp = 0;
  2207. X
  2208. X            /* allow for more than two newlines */
  2209. X            while (*bp == '\n') {
  2210. X                tmp++;
  2211. X                if (++bp == end_buf) {
  2212. X                    DO_END_OF_BUF
  2213. X                }
  2214. X                if (bp == end_data) {
  2215. X                    DO_END_OF_DATA
  2216. X                }
  2217. X            }
  2218. X            iop->off = bp;
  2219. X            bp -= 1 + tmp;
  2220. X        } else if (bp != iop->buf && bp[-1] != '\n') {
  2221. X            warning("record not terminated");
  2222. X            iop->off = bp + 2;
  2223. X        } else {
  2224. X            bp--;
  2225. X            iop->off = bp + 2;
  2226. X        }
  2227. X    } else {
  2228. X        while (*bp++ != rs) {
  2229. X            if (bp == end_buf) {
  2230. X                DO_END_OF_BUF
  2231. X            }
  2232. X            if (bp == end_data) {
  2233. X                DO_END_OF_DATA
  2234. X            }
  2235. X        }
  2236. X        if (*--bp != rs) {
  2237. X            warning("record not terminated");
  2238. X            bp++;
  2239. X        }
  2240. X        iop->off = bp + 1;
  2241. X    }
  2242. X    if (start == iop->secbuf) {
  2243. X        len = bp - iop->buf;
  2244. X        if (len > 0) {
  2245. X            used = last - start;
  2246. X            while (len + used > iop->secsiz) {
  2247. X                iop->secsiz *= 2;
  2248. X                erealloc(iop->secbuf,char *,iop->secsiz,"get2");
  2249. X            }
  2250. X            last = iop->secbuf + used;
  2251. X            start = iop->secbuf;
  2252. X            memcpy(last, iop->buf, len);
  2253. X            last += len;
  2254. X        }
  2255. X    } else
  2256. X        last = bp;
  2257. X    *last = '\0';
  2258. X    *res = start;
  2259. X    return last - start;
  2260. X}
  2261. X
  2262. XNODE *
  2263. Xdo_getline(tree)
  2264. XNODE *tree;
  2265. X{
  2266. X    struct redirect *rp;
  2267. X    IOBUF *iop;
  2268. X    int cnt;
  2269. X    NODE **lhs;
  2270. X    int redir_error = 0;
  2271. X
  2272. X    if (tree->rnode == NULL) {     /* no redirection */
  2273. X        iop = nextfile();
  2274. X        if (iop == NULL)        /* end of input */
  2275. X            return tmp_number((AWKNUM) 0.0);
  2276. X    } else {
  2277. X        rp = redirect(tree->rnode, &redir_error);
  2278. X        if (rp == NULL && redir_error)    /* failed redirect */
  2279. X            return tmp_number((AWKNUM) -1.0);
  2280. X        iop = rp->iop;
  2281. X        getline_redirect++;
  2282. X    }
  2283. X    if (tree->lnode == NULL) {    /* no optional var. -- read in $0 */
  2284. X        if (inrec(iop) != 0) {
  2285. X            getline_redirect = 0;
  2286. X            return tmp_number((AWKNUM) 0.0);
  2287. X        }
  2288. X    } else {            /* read in a named variable */
  2289. X        char *s = NULL;
  2290. X
  2291. X        lhs = get_lhs(tree->lnode, 1);
  2292. X        cnt = get_a_record(&s, iop);
  2293. X        if (!getline_redirect) {
  2294. X            assign_number(&NR_node->var_value,
  2295. X                NR_node->var_value->numbr + 1.0);
  2296. X            assign_number(&FNR_node->var_value,
  2297. X                FNR_node->var_value->numbr + 1.0);
  2298. X        }
  2299. X        if (cnt == EOF) {
  2300. X            getline_redirect = 0;
  2301. X            free(s);
  2302. X            return tmp_number((AWKNUM) 0.0);
  2303. X        }
  2304. X        *lhs = make_string(s, strlen(s));
  2305. X        do_deref();
  2306. X        /* we may have to regenerate $0 here! */
  2307. X        if (field_num == 0)
  2308. X            set_record(fields_arr[0]->stptr, fields_arr[0]->stlen);
  2309. X        field_num = -1;
  2310. X    }
  2311. X    getline_redirect = 0;
  2312. X    return tmp_number((AWKNUM) 1.0);
  2313. X}
  2314. END_OF_FILE
  2315.   if test 17467 -ne `wc -c <'./io.c'`; then
  2316.     echo shar: \"'./io.c'\" unpacked with wrong size!
  2317.   fi
  2318.   # end of './io.c'
  2319. fi
  2320. if test -f './missing.d/memcpy.c' -a "${1}" != "-c" ; then 
  2321.   echo shar: Will not clobber existing file \"'./missing.d/memcpy.c'\"
  2322. else
  2323.   echo shar: Extracting \"'./missing.d/memcpy.c'\" \(261 characters\)
  2324.   sed "s/^X//" >'./missing.d/memcpy.c' <<'END_OF_FILE'
  2325. X/*
  2326. X * memcpy --- copy strings.
  2327. X *
  2328. X * We supply this routine for those systems that aren't standard yet.
  2329. X */
  2330. X
  2331. Xchar *
  2332. Xmemcpy (dest, src, l)
  2333. Xregister char *dest, *src;
  2334. Xregister int l;
  2335. X{
  2336. X    register char *ret = dest;
  2337. X
  2338. X    while (l--)
  2339. X        *dest++ = *src++;
  2340. X
  2341. X    return ret;
  2342. X}
  2343. END_OF_FILE
  2344.   if test 261 -ne `wc -c <'./missing.d/memcpy.c'`; then
  2345.     echo shar: \"'./missing.d/memcpy.c'\" unpacked with wrong size!
  2346.   fi
  2347.   # end of './missing.d/memcpy.c'
  2348. fi
  2349. echo shar: End of archive 11 \(of 16\).
  2350. cp /dev/null ark11isdone
  2351. MISSING=""
  2352. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ; do
  2353.     if test ! -f ark${I}isdone ; then
  2354.     MISSING="${MISSING} ${I}"
  2355.     fi
  2356. done
  2357. if test "${MISSING}" = "" ; then
  2358.     echo You have unpacked all 16 archives.
  2359.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  2360. else
  2361.     echo You still must unpack the following archives:
  2362.     echo "        " ${MISSING}
  2363. fi
  2364. exit 0
  2365. exit 0 # Just in case...
  2366.